# -*- coding: utf-8 -*-
import datetime
import time
import random
from operations.weixin import *
from xml.etree import ElementTree
from services.weixin.weixin_service import WeixinService
from sdk import WeixinSDK
from config import WeixinAppConfig

class WeixinOperation():
	# Exception Aop inject 
	__metaclass__ = OperationAop

	def __init__(self):
		self._weixinService = WeixinService()

	def saveData(self,xmlData):
		xmlRoot = ElementTree.fromstring(xmlData)
		msgType = xmlRoot.find("MsgType").text
		diction = self.__xml2dic(xmlRoot)
		self.__saveSwitch(msgType,diction)
		return self.__getResponse(msgType,xmlRoot)

	def createMenu(self,menu):
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		return weixinSDK.createMenu(menu)

	def batchUpdateUser(self):
		nextOpenId = ""
		users = []
		totalCount = None
		curCount = 0
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		while curCount != totalCount:
			followers = weixinSDK.getFollowers(nextOpenId)
			followerIds = followers["data"]["openid"]
			totalCount = followers["total"]
			curCount += followers["count"]
			nextOpenId = followers["next_openid"]
			for openid in followerIds:
				user = weixinSDK.getUserInfo(openid)
				users.append(user)

			self._weixinService.batchUpdateUsers(users)
			

	def batchInsertUser(self):
		nextOpenId = ""
		users = []
		totalCount = None
		curCount = 0
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		while curCount != totalCount:
			followers = weixinSDK.getFollowers(nextOpenId)
			followerIds = followers["data"]["openid"]
			totalCount = followers["total"]
			curCount += followers["count"]
			nextOpenId = followers["next_openid"]
			for openid in followerIds:
				user = weixinSDK.getUserInfo(openid)
				users.append(user)

			self._weixinService.batchInsertUsers(users)


	def __xml2dic(self,xmlRoot):
		diction = {}
		nodes = xmlRoot.getchildren()
		for node in nodes:
			diction[node.tag] = '' if node.text is None else node.text
		return diction

	def __saveSwitch(self,key,diction):
		message = {
			MsgType.Text:lambda:self._weixinService.addText(diction),
			MsgType.Image:lambda:self._weixinService.addImage(diction),
			MsgType.Voice:lambda:self._weixinService.addVoice(diction),
			MsgType.Video:lambda:self._weixinService.addVideo(diction),
			MsgType.Location:lambda:self._weixinService.addMsgLocation(diction),
			MsgType.Link:lambda:self._weixinService.addLink(diction),
			MsgType.Event:lambda:self.__saveEvent(diction)
		}
		message[key]()

	def __saveEvent(self,diction):
		eventType = diction['Event']
		events = {
				EventType.Click:lambda:self._weixinService.addClickEvent(diction),
				EventType.Subscribe:lambda:self.__subscribeEvent(diction),#self._weixinService.addSubscribeEvent(diction),
				EventType.Unsubscribe:lambda:self.__unsubscribeEvent(diction),#self._weixinService.addUnsubscribeEvent(diction),
				EventType.Scan:lambda:self._weixinService.addScanEvent(diction),
				EventType.Location:lambda:self._weixinService.addLocationEvent(diction)
		}
		
		return events[eventType]()

	def __subscribeEvent(self, diction):
		self._weixinService.addSubscribeEvent(diction)
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		user = weixinSDK.getUserInfo(diction['FromUserName'])
		self._weixinService.addUser(user)

	def __unsubscribeEvent(self, diction):
		self._weixinService.addUnsubscribeEvent(diction)
		self._weixinService.delUser(diction['FromUserName'])


	def __getResponse(self,msgType,xmlRoot):
		toUser = xmlRoot.find("ToUserName").text
		fromUser = xmlRoot.find("FromUserName").text
		dateNow = datetime.datetime.now()
		createTime = int(time.mktime(dateNow.timetuple()))
		cacheKey = "%s_eventKey" % fromUser

		if(msgType == MsgType.Event):
			eventType = xmlRoot.find("Event").text
			supportEventTypes = [EventType.Subscribe,EventType.Unsubscribe,EventType.Scan,EventType.Location]
			if eventType in supportEventTypes:
				return self.__eventTextResponse(toUser,fromUser,createTime,eventType)

			# 只处理click event
			eventKey = xmlRoot.find("EventKey").text #V[ReplyType]_[MsgType]
			replyType = str(eventKey[1:2]).upper()

			#将ReplyType 写入缓存,以备处理用户回复
			RedisCacheManager.setCacheStr(cacheKey,eventKey)

			#replyContent = "%s10" % replyType #replyType[2]pageFlag[1]orderIndex[1]
			responseData = self._weixinService.getResponseData(eventKey)
			if len(responseData) == 0:
				raise Exception("EventKey: %s is undefined!")
			resMsgKey = responseData[0]["MsgType"]

			responses = {
				MsgType.Text:lambda:self.__textResponse(toUser,fromUser,createTime,None,responseData),
				MsgType.Image:lambda:self.__imageResponse(toUser,fromUser,createTime,responseData),
				MsgType.Voice:lambda:self.__voiceResponse(toUser,fromUser,createTime,responseData),
				MsgType.Video:lambda:self.__videoResponse(toUser,fromUser,createTime,responseData),
				MsgType.Music:lambda:self.__musicResponse(toUser,fromUser,createTime,responseData),
				MsgType.News:lambda:self.__newsResponse(toUser,fromUser,createTime,responseData)
			}

			return responses[resMsgKey]()

		if msgType == MsgType.Text: # 只处理回复的文本消息
			replyContent = xmlRoot.find("Content").text
			#如果回复内容为BD开头 做硬件绑定
			#if replyContent[0:2].upper() == ReplyType.BindWare:
			#	return self.__getReplyBindWareContent(fromUser,replyContent[3:])

			#从缓存中取出ReplyType 
			cacheEventKey = RedisCacheManager.getCacheStr(cacheKey)
			if cacheEventKey is None: # 不存在缓存的ReplyType
				return "提示信息:当前无任何操作!"

			responseData = self._weixinService.getResponseData(cacheEventKey)
			if len(responseData) == 0:
				raise Exception("EventKey: %s is undefined!" % eventKey)

			response = self.__textResponse(toUser,fromUser,createTime,replyContent,responseData)
			return response

		return None

	def __eventTextResponse(self,toUser,fromUser,createTime,eventType):
		eventTypes = {
			EventType.Subscribe:lambda:self.__subscribeEventContent(),#self._weixinService.addSubscribeEvent(diction),
			EventType.Unsubscribe:lambda:self.__unsubscribeEventContent(),#self._weixinService.addUnsubscribeEvent(diction),
			EventType.Scan:lambda:self.__scanEventContent(),
			EventType.Location:lambda:self.__locationEventContent()
		}
		resContent = eventTypes[eventType]()
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
						</xml>''' % (fromUser,toUser,createTime,MsgType.Text,resContent)
		return xmlResponse

	def __subscribeEventContent(self):
		return "欢迎订阅ETLinking 微信服务号特供游戏专区之奴隶买卖!"

	def __unsubscribeEventContent(self):
		return ""

	def __scanEventContent(self):
		return "欢迎订阅ETLinking 微信服务号特供游戏专区之奴隶买卖!"

	def __locationEventContent(self):
		return "欢迎订阅ETLinking 微信服务号特供游戏专区之奴隶买卖!"

	def __textResponse(self,toUser,fromUser,createTime,replyContent,responseData):
		dbData = responseData[0]
		resContent = None
		if replyContent == None:
			resContent = self.__getRequestResponse(fromUser)
		else:
			resContent = self.__getReplyResponse(fromUser,replyContent)

		if resContent == None:
			resContent = ""
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
						</xml>''' % (fromUser,toUser,createTime,dbData['MsgType'],resContent)
		return xmlResponse

	def __imageResponse(self,toUserName,fromUserName,createTime,responseData):
		dbData = responseData[0]
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Image>
							<MediaId><![CDATA[%s]]></MediaId>
							</Image>
						</xml>''' % (fromUserName,toUserName,createTime,dbData["MsgType"],dbData["MediaId"])
		return xmlResponse

	def __voiceResponse(self,toUserName,fromUserName,createTime,responseData):
		dbData = responseData[0]
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Voice>
							<MediaId><![CDATA[%s]]></MediaId>
							</Voice>
						</xml>''' % (fromUserName,toUserName,createTime,dbData["MsgType"],dbData["MediaId"])
		return xmlResponse

	def __videoResponse(self,toUserName,fromUserName,createTime,responseData):
		dbData = responseData[0]
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Video>
							<MediaId><![CDATA[%s]]></MediaId>
							<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
							</Video> 
						</xml>''' % (fromUserName,toUserName,createTime,dbData["MsgType"],dbData["MediaId"],dbData["ThumbMediaId"])
		return xmlResponse

	def __musicResponse(self,toUserName,fromUserName,createTime,responseData):
		dbData = responseData[0]
		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Music>
							<Title><![CDATA[%s]]></Title>
							<Description><![CDATA[%s]]></Description>
							<MusicUrl><![CDATA[%s]]></MusicUrl>
							<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
							<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
							</Music>
						</xml>''' % (fromUserName,toUserName,createTime,dbData["MsgType"],dbData["Title"],
						dbData["Description"],dbData["MusicUrl"],dbData["HQMusicUrl"],dbData["ThumbMediaId"])
		return xmlResponse

	def __newsResponse(self,toUserName,fromUserName,createTime,responseData):
		items = []
		for dbData in responseData:
			item = '''<item>
						<Title><![CDATA[%s]]></Title> 
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
					</item>''' % (dbData["Title"],dbData["Description"],dbData["PicUrl"],dbData["Url"])

			items.append(item)

		xmlResponse = '''<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<ArticleCount>%s</ArticleCount>
							<Articles>%s</Articles>
						</xml>''' % (fromUserName,toUserName,createTime,responseData[0]["MsgType"],str(len(items)),''.join(items))

		return xmlResponse

	#首次点击按键时触发
	def __getRequestResponse(self,fromUser):
		#取缓存中ReplyType 如果是BD(绑定硬件,则不用解析,直接做绑定)
		#不用判断是否过期，点击按钮，存入缓存后直接触发
		cacheKey = "%s_eventKey" % fromUser
		cacheEventKey = RedisCacheManager.getCacheStr(cacheKey)
		cacheReplyType = str(cacheEventKey[1:3]).upper()
		cacheReplies = {
				#我的状态
				ReplyType.UserStatus:lambda:self.__getUserStatusContent(fromUser),
				#我的奴隶
				ReplyType.UserSlave:lambda:self.__getUserSlaversContent(fromUser,0),
				#购买奴隶
				ReplyType.BuySlave:lambda:self.__getSlaversContent(fromUser,0),
				#我要赎身
				ReplyType.Redeem:lambda:self.__getRedeemContent(fromUser),
				#折磨奴隶
				ReplyType.PunishSlave:lambda:self.__getRandomPunishContent(fromUser),
				#释放奴隶
				#ReplyType.FreeSlave:lambda:self.
				#安抚奴隶
				#ReplyType.PacifySlave:lambda:self.
				#讨好主人
				ReplyType.PleaseMaster:lambda:self.__getRandomPleaseContent(fromUser),
				#求包养
				ReplyType.ForNurturing:lambda:self.__getNurturingContent(fromUser),
				#奴隶签到
				ReplyType.SignIn:lambda:self.__getSignInContent(fromUser),
				#绑定硬件
				ReplyType.BindWare:lambda:self.__getBindWareContent(fromUser)
			}
		return cacheReplies[cacheReplyType]()

	#我的状态
	def __getUserStatusContent(self,fromUser):
		master = self._weixinService.getUserMaster(fromUser)
		userInfo = self._weixinService.getUserInfo(fromUser)

		userId = userInfo["id"]
		priceRank = self._weixinService.getUserPriceRank(userId)
		assetRank = self._weixinService.getUserAssetRank(userId)
		slaverCount = self._weixinService.getUserSlaversCount(fromUser)
		masterDesc = ""
		if master != None:
			masterDesc = "%(nickname)s (%(price)dcal)" % master
		
		replyContent = '''您的状态:%(statusDesc)s
							总资产:%(asset)dcal
							资产排名:%(assetRank)d
							身价:%(price)dcal
							身价排名:%(priceRank)d
							主人:%(masterDesc)s
							奴隶:%(slaverCount)d 个
						''' % \
						{
							"statusDesc":"求包养" if userInfo["status"] == UserStatus.Nurturing else "",
							"asset":userInfo["asset"],
							"assetRank":assetRank,
							"price":userInfo["price"],
							"priceRank":priceRank,
							"masterDesc":masterDesc,
							"slaverCount":slaverCount
						}

		return replyContent.replace('\t','')

	#查看我的奴隶列表
	def __getUserSlaversContent(self,fromUser,pageIndex):
		slaversCount = self._weixinService.getUserSlaversCount(fromUser)
		if slaversCount == 0:
			return "您的奴隶都跑光啦! 您空有一身本领无处施展！纠结的人生!唉！！"

		pageSize = 10
		pageIndex = pageIndex + 1
		users = self._weixinService.getUserSlavers(fromUser,pageIndex,pageSize)
		
		userIds = []
		items = []
		for i in range(0, len(users)):
			user = users[i]
			userIds.append(user["id"])
			order = str(i).rjust(2,"0")
			item = "%s: %s(%dcal)" % (order,user['nickname'],user["price"])
			items.append(item)
			if (i+1) == pageSize:
				desc = "查看更多..."
				item = "%d: %s" % ((pageIndex + 10),desc)
				items.append(item)
		
		#缓存 当前我的奴隶列表
		cacheKey = "%s_%s_uid" % (ReplyType.UserSlave,fromUser)
		RedisCacheManager.setCacheList(cacheKey,userIds)

		replyTmp = '''您可以回复"[ZM|AF|SF]序列号"快速"[折磨|安抚|释放]"选定奴隶
						如回复：ZM00  即可折磨列表中编号为00奴隶：
						[contentList]

					'''
		resContent = replyTmp.replace('\t','').replace("[contentList]","\n".join(items))
		return resContent

	#查找所有奴隶
	def __getSlaversContent(self,fromUser,pageIndex):
		pageSize = 10
		pageIndex = pageIndex + 1
		users = self._weixinService.getSlavers(fromUser,pageIndex,pageSize)
		
		userIds = []
		items = []
		for i in range(0, len(users)):
			user = users[i]
			userIds.append(user["id"])

			order = str(i).rjust(2,"0")
			nurturingDesc = "包养价" if user['status'] == UserStatus.Nurturing else ""
			item = "%s: %s(%s%dcal)" % (order,user['nickname'],nurturingDesc,user["price"])
			items.append(item)
			if (i+1) == pageSize:
				desc = "查看更多..."
				item = "%d: %s" % ((pageIndex + 10),desc)
				items.append(item)
		
		#缓存 当前我的奴隶列表
		cacheKey = "%s_%s_uid" % (ReplyType.BuySlave,fromUser)
		RedisCacheManager.setCacheList(cacheKey,userIds)

		replyTmp = '''您可以回复序列号快速购买奴隶：
						[contentList]
					'''
		resContent = replyTmp.replace('\t','').replace("[contentList]","\n".join(items))
		return resContent

		#查找所有奴隶
	def __getSlaversByNameContent(self,fromUser,slaverName):
		pageSize = 10
		users = self._weixinService.getUserSlaversByName(fromUser,slaverName.strip())
		
		userIds = []
		items = []
		for i in range(0, len(users)):
			user = users[i]
			userIds.append(user["id"])

			order = str(i).rjust(2,"0")
			nurturingDesc = "包养价" if user['status'] == UserStatus.Nurturing else ""
			item = "%s: %s(%s%dcal)" % (order,user['nickname'],nurturingDesc,user["price"])
			items.append(item)
		
		#缓存 当前我的奴隶列表
		cacheKey = "%s_%s_uid" % (ReplyType.BuySlave,fromUser)
		RedisCacheManager.setCacheList(cacheKey,userIds)

		replyTmp = '''您可以回复序列号快速购买奴隶：
						[contentList]
					'''
		resContent = replyTmp.replace('\t','').replace("[contentList]","\n".join(items))
		return resContent

	#我要赎身
	def __getRedeemContent(self,fromUser):
		master = self._weixinService.getUserMaster(fromUser)
		if master == None:
			return "您还是自由身!是不是很久没有在奴隶买卖中冒泡了"

		userInfo = self._weixinService.getUserInfo(fromUser)
		# 资产比身价低,不能赎身
		if userInfo['asset'] < userInfo['price']: 
			return "手头拮据,不够赎身哦!开动你的聪明才智,努力挣钱吧!为了解放一代奴隶奋斗吧!"


		self._weixinService.redeem(master["id"],userInfo["id"],userInfo["price"])

		resContent = '您给 %s %dcal 为自己赎身,您现在是自由身。自由无处不在！' % \
						(master["nickname"],userInfo["price"])
		

		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		#调接口:给主人发消息
		masterContent = '您的奴隶 %s 自掏腰包 %dcal 为自己赎身,他已逃出你的魔掌!' % \
						(userInfo["nickname"],userInfo["price"])
		weixinSDK.sendTextMsg(master["openid"],masterContent)
		
		return resContent

	#随机折磨一个奴隶
	def __getRandomPunishContent(self,fromUser,slaverId = None):
		slaver = None
		if slaverId == None:
			#随机找一个奴隶
			slaver = self._weixinService.getRandomUserSlaver(fromUser)
		else:
			slaver = self._weixinService.getUserSlaverById(fromUser,slaverId)
			if slaver == None:
				return "您的这个奴隶逃跑了?被别人买了?"

		if slaver == None:
			return "您的奴隶都跑光啦! 您空有一身本领无处施展！纠结的人生!唉！！"

		userInfo = self._weixinService.getUserInfo(fromUser)
		#随机找一个折磨奴隶的方法，
		punish = self._weixinService.getRandomActivity(ActivityType.Punish)
		punishEffect = int(punish["effect"])
		slaverMsgTmp = punish["slaver_msg"]
		userMsgTmp = punish["master_msg"]
		escapeMasterMsg = ""
		escapeSlaverMsg = ""

		if punishEffect == 2:#可能跑掉
			isEscape = random.randint(1, 10) > 8
			if isEscape: # 随机逃跑了
				escapeMasterMsg = "很不幸 %(nickname)s 从您手中逃跑了" % slaver
				escapeSlaverMsg = "您受不了这样非人的虐待,逃出了 %(nickname)s 的魔掌" % userInfo
				isSteal = random.randint(1,10) > 8
				stealMoney = 0
				if isSteal:
					stealMoney = int(int(userInfo["asset"]) * (random.uniform(1, 10)/100))
					if stealMoney != 0:
						escapeMasterMsg = escapeMasterMsg + ",顺手牵走了您 %dcal" % stealMoney
						escapeSlaverMsg = escapeSlaverMsg + ",顺手拿了他 %dcal,他暴跳如雷!!" % stealMoney
				
				self._weixinService.escape(slaver["id"],userInfo["id"],stealMoney)

		resultDict = {
			"masterName":userInfo["nickname"],
			"slaverName":slaver["nickname"],
			"escapeMasterMsg":escapeMasterMsg,
			"escapeSlaverMsg":escapeSlaverMsg
		}

		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		resSlaverContent = slaverMsgTmp % resultDict
		weixinSDK.sendTextMsg(slaver["openid"],resSlaverContent)

		resContent = userMsgTmp % resultDict
		return resContent

	#释放奴隶
	def __getFreeContent(self,fromUser,slaverId):
		slaver = self._weixinService.getUserSlaverById(fromUser,slaverId)
		if slaver == None:
			return "您的这个奴隶逃跑了?被别人买了?"

		#释放奴隶
		userInfo = self._weixinService.getUserInfo(fromUser)
		recyclePrice = int(int(slaver["price"]) * (random.uniform(8,9)/10))
		self._weixinService.freeSlaver(userInfo["id"],slaver["id"],recyclePrice)

		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		resSlaverContent = "由于你的懒惰,您的主人 %s 不要你了!以折扣价 %dcal的价格把放您回归自然!" % (userInfo["nickname"],recyclePrice)
		weixinSDK.sendTextMsg(slaver["openid"],resSlaverContent)

		resContent = "您成功释放了您的奴隶 %s,回收资金 %dcal!" % (slaver["nickname"],recyclePrice)
		return resContent



	#安抚奴隶
	def __getPacifyContent(self,fromUser,slaverId = None):
		slaver = None
		if slaverId == None:
			#随机找一个奴隶
			slaver = self._weixinService.getRandomUserSlaver(fromUser)
		else:
			slaver = self._weixinService.getUserSlaverById(fromUser,slaverId)
			if slaver == None:
				return "您的这个奴隶逃跑了?被别人买了?"

		if slaver == None:
			return "您的奴隶都跑光啦! 您空有一身本领无处施展！纠结的人生!唉！！"

		userInfo = self._weixinService.getUserInfo(fromUser)
		#随机找一个安抚奴隶的方法，
		pacify = self._weixinService.getRandomActivity(ActivityType.Pacify)
		pacifyEffect = int(pacify["effect"])
		slaverMsgTmp = pacify["slaver_msg"]
		userMsgTmp = pacify["master_msg"]
		slaverOpenId = slaver["openid"]

		resultDict = {
			"masterName":userInfo["nickname"],
			"slaverName":slaver["nickname"]
		}

		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		#punishEffect == 1 奴隶不会跑掉 奴隶接受了惩罚 他也认了  
		resSlaverContent = slaverMsgTmp % resultDict
		weixinSDK.sendTextMsg(slaverOpenId,resSlaverContent)

		resContent = userMsgTmp % resultDict
		return resContent

	#讨好主人 随机一个讨好方式
	def __getRandomPleaseContent(self,fromUser):
		master = self._weixinService.getUserMaster(fromUser)
		if master == None:
			return '你现在是自由身!不用看别人的脸色做事儿！'

		userInfo = self._weixinService.getUserInfo(fromUser)
		#随机找一个讨好主人的方法，
		please = self._weixinService.getRandomActivity(ActivityType.Please)
		pleaseEffect = please["effect"] #打赏的范围 min-max
		masterMsgTmp = please["master_msg"]
		userMsgTmp = please["slaver_msg"]
		masterOpenid = master["openid"]
		rewardMasterMsg = ""
		rewardSlaverMsg = ""

		if pleaseEffect != "":#打赏的范围 min-max
			rewardRange = pleaseEffect.split('-')
			rewardMin = int(rewardRange[0])
			rewardMax = int(rewardRange[1])

			#随机给奴隶一些打赏 您给奴隶 %(slaverName)s 给您揉揉腿,您很高兴!%(rewardMasterMsg)s
			rewardMoney = random.randint(rewardMin,rewardMax)
			if master["asset"] > rewardMoney:
				rewardMasterMsg = "给你打赏 %dcal,拿去买糖吃吧!" % rewardMoney
				rewardSlaverMsg = "打赏我 %dcal买糖吃^_^!" % rewardMoney
				self._weixinService.reward(master["id"],userInfo["id"],rewardMoney)

		resultDict = {
			"masterName":master["nickname"],
			"slaverName":userInfo["nickname"],
			"rewardMasterMsg":rewardMasterMsg,
			"rewardSlaverMsg":rewardSlaverMsg
		}

		#调接口:给奴隶发消息
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		resMasterContent = masterMsgTmp % resultDict
		weixinSDK.sendTextMsg(masterOpenid,resMasterContent)
		
		resContent = userMsgTmp % resultDict
		return resContent

	#求包养
	def __getNurturingContent(self,fromUser):
		#前提是没有主人
		master = self._weixinService.getUserMaster(fromUser)
		if master != None:
			return "您已经被 %(nickname)s 包养很多年,是不是被冷落了?赶紧讨好一下他吧!说不定还有什么惊喜呢!!" % master

		#求包养的人，在奴隶市场中的排名会在前面,同样身价会相应的降低
		self._weixinService.setUserStatus(fromUser,UserStatus.Nurturing)

		resContent = "您已经在奴隶市场上挂上【求包养】的牌子,您的身价因此也大大折扣了!"
		return resContent
	
	#每日签到
	def __getSignInContent(self,fromUser):
		#签到是奴隶挣钱的一种方法，但给的钱相对少些
		resultSignIn = self._weixinService.signIn(fromUser)
		isSignIn = resultSignIn["isSignIn"]
		signInMoney = resultSignIn["signInMoney"]

		#签到也可以把绑定硬件的昨天数据同步过来
		syncMoney = self._weixinService.syncETData(fromUser)
		
		resContent = ""
		syncDesc = ""
		if syncMoney > 0:
			syncDesc = "同时从你的硬件设备中同步%dcal,今天收获不小," % syncMoney

		if isSignIn:
			resContent = "您今天已签到过,赚得 %dcal 奖励,%s请明天再来吧!" % (signInMoney,syncDesc)
		else:
			resContent = "恭喜签到成功,赚得 %dcal 奖励,%s明天继续哦!" % (signInMoney,syncDesc)
		return resContent

	#绑定硬件
	def __getBindWareContent(self,fromUser):
		# 返回绑定硬件的一些说明性信息
		resContent = '''当您持有了我们的产品 ET·Go, 您平时运动数据在这里就会转换成您的资产,从此再也不用担心资产不足无法体验奴隶买卖的乐趣!
						绑定方法：1、在我们的<a href="www.etlinking.com">官方网站</a>注册一个帐号;
								  2、在您的ET帐号下绑定您的<a href="etspace.taobao.com">ET·Go</a>;
								  3、回复:ET帐号 ET·Go序列号;
								  4、回复:QXBD 可以取消硬件绑定;
						官方网址:<a href="www.etlinking.com">www.etlinking.com</a>
						官方淘宝:<a href="etspace.taobao.com">etspace.taobao.com</a>
		'''
		return resContent.replace("\t","")



	# 只处理回复的文本消息
	def __getReplyResponse(self,fromUser,replyContent):
		#取缓存中取出eventKey
		cacheKey = "%s_eventKey" % fromUser
		cacheEventKey = RedisCacheManager.getCacheStr(cacheKey)
		# 不存在缓存的ReplyType
		if cacheEventKey is None: 
			return "提示信息:当前无任何操作!"

		cacheReplyType = str(cacheEventKey[1:3]).upper()
		#只支持 我的奴隶 购买奴隶  绑定硬件 三个栏目的交互
		replyTypes = [ReplyType.UserSlave,ReplyType.BuySlave,ReplyType.BindWare]
		if cacheReplyType in replyTypes:
			supportReplies = {
				# 回复 我的奴隶
				ReplyType.UserSlave:lambda:self.__getReplyUserSlaverContent(fromUser,replyContent),
				# 回复 购买奴隶
				ReplyType.BuySlave:lambda:self.__getReplyBuySlaverContent(fromUser,replyContent),
				# 回复 绑定硬件
				ReplyType.BindWare:lambda:self.__getReplyBindWareContent(fromUser,replyContent)
			}
			return supportReplies[cacheReplyType]()

		#其他回复内容，直接pass
		return None
		
	#回复 我的奴隶
	def __getReplyUserSlaverContent(self,fromUser,replyContent):
		
		import re
		match = re.match(r'\d', replyContent)
		if match: #直接输入的分页数字
			pageIndex = int(replyContent) - 10
			return self.__getUserSlaversContent(fromUser,pageIndex)

		replyType = str(replyContent[0:2]).upper()
		#只支持 折磨奴隶 释放奴隶  安抚奴隶 三个栏目的交互
		replyTypes = [ReplyType.PunishSlave,ReplyType.FreeSlave,ReplyType.PacifySlave]
		if replyType in replyTypes:
			orderIndex = int(replyContent[2:])
			#从缓存中取出当前索引对应的奴隶Id
			cacheKey = "%s_%s_uid" % (ReplyType.UserSlave,fromUser)
			cacheUIds = RedisCacheManager.getCacheList(cacheKey)
			userId = cacheUIds[orderIndex]

			supportReplies = {
				# 回复 折磨奴隶
				ReplyType.PunishSlave:lambda:self.__getRandomPunishContent(fromUser,userId),
				# 回复 释放奴隶
				ReplyType.FreeSlave:lambda:self.__getFreeContent(fromUser,userId),
				# 回复 安抚奴隶
				ReplyType.PacifySlave:lambda:self.__getPacifyContent(fromUser,userId)
			}
			return supportReplies[replyType]()

		#其他回复内容，直接pass
		return None

	#回复购买奴隶的序号或分页
	def __getReplyBuySlaverContent(self,fromUser,replyContent):
		#按名称
		import re
		match = re.match(r'\d', replyContent)
		if not match: #直接输入的分页数字
			return self.__getSlaversByNameContent(fromUser,replyContent)

		#从缓存中取出当前索引对应的奴隶Id
		orderIndex = int(replyContent)
		if orderIndex > 9: #分页请求
			pageIndex = orderIndex - 10
			return self.__getSlaversContent(fromUser,pageIndex);

		cacheKey = "%s_%s_uid" % (ReplyType.BuySlave,fromUser)
		cacheUIds = RedisCacheManager.getCacheList(cacheKey)
		userId = cacheUIds[orderIndex]

		#建立主仆关系
		slaver = self._weixinService.getUserInfoById(userId)
		master = self._weixinService.getUserMaster(slaver["openid"])
		userInfo = self._weixinService.getUserInfo(fromUser)

		masterId = None
		masterName = ""
		masterDesc = ""
		slaverDesc = "%s 收为奴隶" % userInfo["nickname"]
		if master != None:
			masterId = master["id"]
			masterName = master["nickname"] 
			masterDesc = "从 %s 手里" % master["nickname"]

		resultDict = {
			"nickName":userInfo["nickname"],
			"slaverName":slaver["nickname"],
			"slaverPrice":slaver["price"],
			"masterName":masterName,
			"masterDesc":masterDesc,
			"slaverDesc":slaverDesc,
			"newPrice":slaver["price"]
		}

		#判断当前userInfo 与 slaver的关系 0:无关系 1:主仆 2:仆主
		relation = self._weixinService.getRelationship(userInfo["id"],slaver["id"])
		if relation == 1:#您是他的主人
			return "奴隶 %(slaverName)s 已经在你的庄园里努力工作了,再看看别的奴隶吧!" % resultDict
		if relation == 2:#您是他的奴隶
			return "怎么?想造反?劝您一句:还是先想办法挣钱吧,争取早日为自己赎身才是正道,%(slaverName)s 现在可是您的主人!" % resultDict

		newPrice = self._weixinService.buySlave(userInfo["id"],slaver["id"],slaver["price"],masterId)
		resultDict["newPrice"] = newPrice

		#调接口:给奴隶发消息
		weixinSDK = WeixinSDK(WeixinAppConfig.AppId,WeixinAppConfig.secret)
		if master != None:
			slaverDesc = "主人 %(masterName)s 以 %(slaverPrice)dcal 的价格卖给了%(nickName)s" % resultDict
			masterContent = "您的奴隶 %(slaverName)s 被 %(nickName)s 以 %(slaverPrice)dcal 购买走!" % resultDict
			weixinSDK.sendTextMsg(master["openid"],masterContent)

		slaverContent = "您被 %(slaverDesc)s,您的身份上涨到 %(newPrice)dcal!" % resultDict
		weixinSDK.sendTextMsg(slaver["openid"],slaverContent)

		resContent = "您花费 %(slaverPrice)dcal %(masterDesc)s购买了奴隶 %(slaverName)s, %(slaverName)s 的身价上涨到 %(newPrice)dcal." % resultDict
		return resContent

	#回复 绑定硬件
	def __getReplyBindWareContent(self,fromUser,replyContent):
		if replyContent.upper() == "QXBD":
			#绑定状态：1:绑定 2:未绑定
			bindStatus = self._weixinService.getBindStatus(fromUser)
			if bindStatus == 2:# 没有绑定硬件
				resContent = '''您还没有绑定硬件哦!
						去<a href="http://etspace.taobao.com">买一个ET·Go!</a>
						去<a href="http://www.etlinking.com">ET官网绑定</a>
						'''
				return resContent.replace("\t","")

			self._weixinService.cancelBind(fromUser)
			return "您的 ET·Go 取消绑定成功!您又断了一条财路!"

		contentArray = replyContent.split(' ')
		userEmail = str(contentArray[0])
		deviceId = str(contentArray[1])

		result = self._weixinService.bindUser(fromUser,userEmail,deviceId)
		#邮箱不存在
		if result == 1:
			resContent = '''对不起!ET不认识您的邮箱!!
						去<a href="http://www.etlinking.com">ET官网</a>注册!
					'''
			return resContent.replace("\t","")

		#邮箱与设备号不匹配
		if result == 2:
			resContent = '''对不起!您的邮箱跟你的设备号不致哦！
						去<a href="http://www.etlinking.com">ET官网</a>修改我的设备号!
					'''
			return resContent.replace("\t","")

		#已绑定成功了
		if result == 3:
			resContent = '''您已成功绑定过ET·Go! 
						去[每日签到]领工资
						'''
			return resContent.replace("\t","")

		#邮箱设备号已被其他微信用户绑定
		if result == 4:
			resContent = '对不起!邮箱设备号已被其他微信用户绑定!'
			return resContent

		syncMoney = self._weixinService.syncETData(fromUser)
		resContent = '''恭喜您!ET·Go 绑定成功!现在您的运动卡路里会源源不断的涌进您的资产,不久的将来您就是奴隶市场上的一颗新星!
					您看,今天就有 %dcal 的资产涌进您的帐户,赶紧带着 ET·Go 去创造您的财富吧！
				''' % syncMoney
		return resContent.replace("\t","")




class MsgType:
	
	#文本消息
	Text = "text"
	#图片消息
	Image = "image"
	#语音消息
	Voice = "voice"
	#视频消息
	Video = "video"
	#地理位置消息
	Location = "location"
	#链接消息
	Link = "link"
	#事件推送
	Event = "event"
	#音乐消息
	Music = "music"
	#图文消息
	News = "news"

class EventType:
	
	#订阅
	#1、EventKey无参数 【关注事件】
	#2、EventKey:Qrscene_二维码参数 【用户未关注时，进行关注后的事件推送】
	Subscribe = "subscribe"
	#取消订阅
	Unsubscribe = "unsubscribe"
	#用户已关注时的事件推送
	#EventKey 是一个32位无符号整数
	Scan = "scan"
	#上报地理位置事件
	Location = "LOCATION"
	#自定义菜单事件
	#EventKey：与自定义菜单接口中KEY值对应
	Click = "CLICK"

class ReplyType:
	#与EventKey 对应

	#我的状态
	UserStatus = "ZT"

	#我的奴隶
	UserSlave = "NL"
	
	#购买奴隶
	BuySlave = "GM"

	#我要赎身
	Redeem = "SS"

	#折磨奴隶
	PunishSlave = "ZM"

	#释放奴隶
	FreeSlave = "SF"

	#安抚奴隶
	PacifySlave = "AF"

	#讨好主人
	PleaseMaster = "TH"

	#求包养
	ForNurturing = "BY"

	#奴隶签到
	SignIn = "QD"

	#绑定硬件
	BindWare = "BD"

		
class ActivityType:
	
	#折磨手段
	Punish = 1

	#讨好手段
	Please = 2

	#安抚手段
	Pacify = 3

class UserStatus:
	
	#取消关注
	Unsubscribe = 0
	
	#关注状态
	Subscribe = 1

	#求包养状态
	Nurturing = 2
		